package com.regulaforensics.date_reminder;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AddDate extends Activity {

	private Long mRowId;
	private EditText mDateNameText;
	private EditText mDateDescText;
	private TextView mDateDisplay;
	private int myDay;
	private int myMonth;
	private int myYear;
	private int contacts;
	private int cont_id;
	private int cont_del;
	private String summaryGlobal;
	private String descGlobal;
	
	static final int DATE_DIALOG_ID = 0;
	
	private static final String TAG = "AddDate";



	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        
        setContentView(R.layout.add_date);
        
        //get textedits
        mDateNameText = (EditText) findViewById(R.id.date_name);
        mDateDescText = (EditText) findViewById(R.id.date_desc);
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        Button mSaveButton = (Button)findViewById(R.id.add_button);
        
        //set up date picker
        final Calendar c = Calendar.getInstance(); 
        myDay = c.get(Calendar.DAY_OF_MONTH);
        myMonth = c.get(Calendar.MONTH);
        myYear = c.get(Calendar.YEAR);
        updateDateDisplay();
//        mydatePicker = (DatePicker)findViewById(R.id.date_picker);
//        /////set up date change listener for Max Date setup
//        mydatePicker.init(myYear-10, myMonth, myDay, new OnDateChangedListener()
//        {
//	        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
//	        {
//	        	if (year > myYear)
//	        		view.updateDate(myYear, myMonth, myDay);
//	        
//	        	if (monthOfYear > myMonth && year == myYear)
//	        		view.updateDate(myYear, myMonth, myDay);
//	        	
//	        	if (dayOfMonth > myDay && year == myYear && monthOfYear == myMonth)
//	        		view.updateDate(myYear, myMonth, myDay);
//	        }
//        }); 
        mRowId = null;
        Bundle extras = getIntent().getExtras();
        mRowId = (bundle == null) ? null : (Long) bundle.getSerializable(ReminderDbAdapter.KEY_ROWID);
        if (extras != null) {
        	mRowId = extras.getLong(ReminderDbAdapter.KEY_ROWID);
        }
        if(mRowId!=null)
        	setTitle(R.string.edit_date_title);
        
        contacts = 0;
        cont_id = 0;
        cont_del = 0;
        
        populateFields();   
        
        mSaveButton.requestFocus();
        Log.d(TAG, "OnCreate with Row =" + mRowId);
    }
    
    
 // updates the date in the TextView
    private void updateDateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(myMonth + 1).append("-")
                    .append(myDay).append("-")
                    .append(myYear).append(" "));
    }
    
    
    public void clickFun(View v){
    	try{
    		String summary = mDateNameText.getText().toString();
    		String desc = mDateDescText.getText().toString();
    		switch (v.getId()) 
	    	{
	    	    case R.id.back_button: 
	    	    	if(((summary.length()!=0)&&(summaryGlobal!=null)&&(summary.compareTo(summaryGlobal)!=0)) ||
	    	    			((summary.length()!=0)&&(summaryGlobal==null)) ||
	    	    			((desc.length()!=0)&&(descGlobal==null)) ||
	    	    			((desc.length()!=0)&&(descGlobal!=null)&&(desc.compareTo(descGlobal)!=0))){
	    	    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	    		builder.setMessage("All data will be lost!\nAre you sure you want to back?")
	    	    		       .setCancelable(false)
	    	    		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	    	    		           public void onClick(DialogInterface dialog, int id) {
	    	    		        	   AddDate.this.finish();
	    	    		           }
	    	    		       })
	    	    		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	    	    		           public void onClick(DialogInterface dialog, int id) {
	    	    		                dialog.cancel();
	    	    		           }
	    	    		       });
	    	    		AlertDialog alert = builder.create();
	    	    		alert.show();
	    	    	}
	    	    	else{
	    	    		finish();
	    	    	}
	    	    	Log.d(TAG, "Back button pressed");
	    	        break;
	    	    case R.id.add_button:
	    	    	
	    	    	if(summary.length()!=0){
	    	    		setResult(RESULT_OK);
		    	    	saveState();
		    	    	finish();
	    	    	}
	    	    	else{
	    	    		Context context = getApplicationContext();  
	    	    	    CharSequence text = "Please, fill Name!";  
	    	    	    int duration = Toast.LENGTH_LONG;  
	    	    	    Toast toast = Toast.makeText(context, text, duration);  
	    	    	    toast.show(); 
	    	    	}
	    	    	Log.d(TAG, "Save button pressed");	
	    	    	break;
	    	    	
	    	    case R.id.dateDisplay:
	    	    	showDialog(DATE_DIALOG_ID);
	    	    	break;
	        }
    	}
    	catch(Exception ex){
    		Context context = getApplicationContext();  
    	    CharSequence text = ex.toString();  
    	    int duration = Toast.LENGTH_LONG;  
    	    Toast toast = Toast.makeText(context, text, duration);  
    	    toast.show();  
    	}
    }

    private void populateFields() {
    	try{
	    	if (mRowId != null) {
	    		ReminderDbAdapter mDbHelper= MyAppDateReminder.getDatabaseAdapter();
	    		Cursor reminder = mDbHelper.fetchTodo(mRowId);
	    	   
	    		summaryGlobal = reminder.getString(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_SUMMARY));
	    	    descGlobal = reminder.getString(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_DESCRIPTION));
	    	    mDateNameText.setText(summaryGlobal);
	    	    mDateDescText.setText(descGlobal);
	    	    //set date picker
	    	    myYear = reminder.getInt(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_YEAR));
	    	    myMonth = reminder.getInt(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_MONTH));
	    	    myDay = reminder.getInt(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_DAY));
	    	    updateDateDisplay();
	    	    //set info about contacts
	    	    contacts = reminder.getInt(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_CONTACTS));
	    	    cont_id = reminder.getInt(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_CONT_ID));
	    	    cont_del = reminder.getInt(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_CONT_DEL));
	    	    
	    	    reminder.close();
	        }
    	}
    	catch(Exception ex){
    		Context context = getApplicationContext();  
    	    CharSequence text = ex.toString();  
    	    int duration = Toast.LENGTH_LONG;  
    	    Toast toast = Toast.makeText(context, text, duration);  
    	    toast.show();  
    	}
    }

    private void saveState() {
    	try{
    	   ReminderDbAdapter mDbHelper= MyAppDateReminder.getDatabaseAdapter();
	       int year = myYear;
	       int month = myMonth;
	       int day = myDay;
	
	       String summary = mDateNameText.getText().toString();
	       String description = mDateDescText.getText().toString();
	       if (mRowId == null) {
	    	   long id = mDbHelper.createTodo(summary, description, year, month, day, contacts, cont_id, cont_del);
	    	   if (id > 0) {
	    		   mRowId = id;
	    	   }
	       } else {
	    	   mDbHelper.updateTodo(mRowId, summary, description, year, month, day, contacts, cont_id, cont_del);
	       }
    	}
    	catch(Exception ex){
    		Context context = getApplicationContext();  
    	    CharSequence text = ex.toString();  
    	    int duration = Toast.LENGTH_LONG;  
    	    Toast toast = Toast.makeText(context, text, duration);  
    	    toast.show();  
    	}
    }
    
 // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    myYear = year;
                    myMonth = monthOfYear;
                    myDay = dayOfMonth;
                    updateDateDisplay();
                }
            };
            
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        myYear, myMonth, myDay);
        }
        return null;
    }

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

    
}